<template>
    <ul class="list" ref="list">
        <li class="item" v-for="item in letters" :key="item" :ref="item"
            @touchstart.prevent="handleTouchstart"
            @touchmove="handleTouchmove"
            @touchend="handleTouchend"
            @click="handleClick"
        >
            {{ item }}
        </li>
    </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      headerHeight: 0,
      touchY: 0,
      letterHeight: 0,
      timer: null
    }
  },
  computed: {
    letters () {
      const letters = []
      for (var key in this.cities) {
        letters.push(key)
      }
      return letters
    }
  },
  methods: {
    handleClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchstart () {
      this.touchStatus = true
    },
    handleTouchmove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // 获取触点到header底部的距离
          this.touchY = e.touches[0].clientY - this.headerHeight
          // 索引
          var index = Math.floor((this.touchY - this.startY) / this.letterHeight)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchend () {
      this.touchStatus = false
    }
  },
  updated () {
    // 获取第一个字母到header底部的距离
    this.startY = this.$refs['A'][0].offsetTop
    // 获取header的高
    this.headerHeight = this.$refs['list'].offsetTop
    // 获取每个字母的高度
    this.letterHeight = this.$refs['B'][0].offsetTop - this.startY
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variables.styl'
.list
    display flex
    flex-direction column
    justify-content center
    position absolute
    top 1.58rem
    right 0
    bottom 0
    width .4rem
    text-align center
    .item
        height .4rem
        line-height .4rem
        color $bgColor
</style>
